<?php
/**
 * 菜单模型
 * panglishan
 * 2020.07.26
 */
namespace App\Models\MainDB;

use Illuminate\Database\Eloquent\Model;

class AdminMenu extends Model{

    protected $table = 'ln_admin_menu';

    protected $primaryKey = 'menu_id';

    protected $fillable = [
        'menu_id',      //菜单编号
        'menu_name',    //菜单名称
        'menu_key',     //菜单key值(用于前端nav)
        'add_time',     //添加时间
        'status',       //状态    1显示2隐藏
        'parent_id',    //父级ID
        'level',        //菜单层级  1顶部2中间层级
        'icon',         //菜单的icon值
        'sort',         //排序数值
    ];

    public $timestamps = false;


    //one to many
    public function hasManyMenus()
    {
         return $this->hasMany('App\Models\MainDB\AdminMenu', 'parent_id', 'menu_id');
    }

    //关联权限模型
    public function hasManyPermission()
    {
        return $this->hasMany('App\Models\MainDB\AdminPermission','menu_id','menu_id');
    }

    /**
     * 查询管理员有权限的一级或二级菜单
     * @param int $level 层级：1：一级菜单；2：二级菜单
     * @param int|array $menuIds -1：不限制；数组则表示指定菜单id
     * @return array
     */
    public function getMenus($level = 1, $menuIds = -1)
    {
        $queryFields = ['menu_id', 'menu_name', 'menu_key', 'icon', 'parent_id'];

        return app('model_menu')
            ->select($queryFields)
            ->where(function ($query) use ($level) {
                if ($level == 1) {
                    $query->where('parent_id', 0);
                } else {
                    $query->where('parent_id', '>', 0);
                }
            })
            ->where(function ($query) use ($menuIds) {
                if ($menuIds != -1) {
                    $query->whereIn('menu_id', $menuIds);
                }
            })
            ->where('status', 1) //显示
            ->orderByDesc('sort')
            ->get()->toArray();
    }
    
    //二级菜单追加到一级菜单
    public function subMenuAppend(&$menus, &$subMenus)
    {
        foreach ($menus as &$menu) {
            foreach ($subMenus as $subMenu) {
                if ($subMenu['parent_id'] == $menu['menu_id']) {
                    $menu['children'][] = $subMenu;
                }
            }
        }
    }
}